<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;
use think\exception\PDOException;
use Exception;
use think\Db;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class Product extends Backend
{

    /**
     * Product模型对象
     * @var \app\common\model\Product\Product
     */
    protected $model = null;

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    /**
     * 商品分类模型
    */
    protected $TypeModel = null;

    /**
     * 商品单位模型
    */
    protected $UnitModel = null;

    /**
     * 快速搜索
    */
    protected $searchFields = ['name','type.name','unit.name'];

    public function _initialize()
    {
        parent::_initialize();
        
        // 加载模型
        $this->model = new \app\common\model\Product\Product;
        $this->TypeModel = model('Product.Type');
        $this->UnitModel = model('Product.Unit');

        $TypeData = $this->TypeModel->order('id','desc')->select();

        $TypeList = [];

        foreach($TypeData as $item)
        {
            $TypeList[$item['id']] = $item['name'];
        }

        // 获取商品单位数据组成下拉框需要的数据
        $UnitList = $this->UnitModel->column('id,name');

        // 获取商品分类数据组成下拉框需要的数据
        $TypeList = $this->TypeModel->column('id,name');

        // 赋值
        $this->assign([
            'flagList' => $this->model->flaglist(),
            'StatusList' => $this->model->statuslist(),
            'UnitList' => $UnitList,
            'TypeList' =>$TypeList
        ]);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 商品列表
    */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->with(['type','unit'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }

        // 输出视图
        return $this->view->fetch();
    }

    /**
     * 添加商品
    */
    public function add()
    {
        if($this->request->isPost())
        {
            // 接收参数
            $params = $this->request->param('row/a');

            $result = $this->model->validate('common/Product/Product')->save($params);
            
            if($result === false)
            {
                // 如果插入失败需要上传的图片删除
                if(!empty($params['thumbs']))
                {
                    // 从字符串转数组
                    $thumbsArr = explode(',',$params['thumbs']);

                    // 过滤数组的空元素
                    $thumbsArr = array_filter($thumbsArr);

                    foreach($thumbsArr as $thumb)
                    {
                        $thumb = ltrim($thumb,'/');

                        @is_file($thumb) && @unlink($thumb);
                    }
                }

                $this->error($this->model->getError());
            }else{
                $this->success();
            }
        }

        return $this->view->fetch();
    }

    /**
     * 编辑商品
     * 
     * @param String $ids 主键
    */
    public function edit($ids = null)
    {
        $ids = $ids ?: $this->request->param('ids','','trim');

        $row = $this->model->find($ids);

        // 找不到数据返回错误信息
        if(!$row)
        {
            $this->error(__('该商品不存在，请重新选择'));
        }

        if($this->request->isPost())
        {
            $params = $this->request->param('row/a');

            $params['id'] = $ids;

            $result = $this->model->validate('common/Product/Product')->isUpdate(true)->save($params);

            if($result === FALSE)
            {
                // 从表单接收的图片
                $thumbs = explode(',',$params['thumbs']);

                // 当前的数据图片
                $OldThumbs = explode(',',$row['thumbs']);

                $thumbs = array_filter($thumbs);

                foreach ($thumbs as $value) {
                    if(!in_array($value,$OldThumbs))
                    {
                        $thumb = ltrim($value,'/');

                        @is_file($thumb) && @unlink($thumb);
                    }
                }

                $this->error(__($this->model->getError()));
            }else{
                // 从表单接收的图片
                $thumbs = explode(',',$params['thumbs']);

                // 当前的数据图片
                $OldThumbs = explode(',',$row['thumbs']);

                $thumbs = array_filter($thumbs);

                foreach($OldThumbs as $item)
                {
                    if(!in_array($item,$thumbs))
                    {
                        $thumb = ltrim($item,'/');

                        @is_file($thumb) && @unlink($thumb);
                    }
                }

                $this->success();
            }
        }
        
        // 赋值
        $this->assign([
            'row' => $row
        ]);

        return $this->view->fetch();
    }

    /**
     * 软删除
     * 
     * @param String $ids 主键
    */
    public function del($ids = null)
    {
        $list = $this->model->where(['id' => ['in',$ids]])->select();

        if(!$list)
        {
            $this->error(__('请选择需要删除的商品'));
        }

        $count = 0;

        // 开启事务
        Db::startTrans();

        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }

            // 提交事务
            Db::commit();

        } catch (PDOException|Exception $e) {
            // 事务回滚
            Db::rollback();

            // 获取错误信息
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
    }

    /**
     * 回收站
    */
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->onlyTrashed()
                ->with(['type','unit'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }

        // 输出视图
        return $this->view->fetch();
    }

    /**
     * 还原
     * 
     * @param str $ids 主键
    */
    public function restore($ids = null)
    {
        if($this->request->isAjax())
        {
            $row = $this->model->onlyTrashed()->where(['id' => ['in',$ids]])->select();

            if(!$row)
            {
                $this->error(__('请选择需要还原的商品'));
            }

            $data = [];

            foreach ($row as $key => $item) {
                $data[] = [
                    'id' => $item['id'],
                    'deletetime' => null
                ];
            }

            $result = $this->model->isUpdate(true)->saveAll($data);

            if($result === FALSE)
            {
                $this->error(__('还原失败'));
            }else{
                $this->success();
            }


        }
    }

    /**
     * 真实删除
    */
    public function destroy($ids = null)
    {
        if($this->request->isAjax())
        {
            $row = $this->model->onlyTrashed()->where(['id' => ['in',$ids]])->select();

            if(!$row)
            {
                $this->error(__('商品不存在'));
            }

            $result = $this->model->destroy($ids,true);

            if($result === FALSE)
            {
                $this->error(__('删除失败'));
            }else{

                // 遍历数据获取图片
                foreach($row as $item)
                {
                    // 把thumbs字段的值转成数组
                    $thumbsArr = !empty($item['thumbs']) ? explode(',',$item['thumbs']) : [];

                    $thumbsArr = array_filter($thumbsArr);

                    foreach($thumbsArr as $val)
                    {
                        $thumb = ltrim($val,'/');

                        @is_file($thumb) && @unlink($thumb);
                    }
                }

                $this->success();
            }
        }
    }
}
